'use strict'
let SystemConfiy = require('../../config/dev.env.config') 
if( process.env.NODE_ENV === 'development' ) {
  SystemConfiy = require('../../config/dev.env.config') 
} else if( process.env.NODE_ENV === 'test' ) {
  SystemConfiy = require('../../config/test.env.config')
} else if( process.env.NODE_ENV === 'production' ) {
  SystemConfiy = require('../../config/prod.env.config')
}
const Redis = require('ioredis')
const uid = require('uid-safe') 
const Store = require("koa-session2/libs/store");
class RedisStore extends Store {
    constructor() {
        super();
        this.redis = new Redis({
            port: SystemConfiy.Redis.port,          // Redis port
            host: SystemConfiy.Redis.host,   // Redis host
            family: SystemConfiy.Redis.family,           // 4 (IPv4) or 6 (IPv6)
            password: SystemConfiy.Redis.password,
            db: SystemConfiy.Redis.db
        });
    }
 
    async get(sid) {
        let data = await this.redis.get(`SESSION:${sid}`);
        return JSON.parse(data);
    }
 
    async set(session, opts) {
        if(!opts.sid) {
            opts.sid = this.getID(24);
        }
        await this.redis.set(`SESSION:${opts.sid}`, JSON.stringify(session));
        return opts.sid;
    }
 
    async destroy(sid) {
        return await this.redis.del(`SESSION:${sid}`);
    }
}
 
module.exports = RedisStore;